<template>
    <div class="container">
        <div class="block">
            <div class="block-header">
                <div class="block-title">账户余额</div>
                <div class="block-more point" @click="
                    $router.push({
                        path: '/longinsure/bill'
                    })
                    ">
                    <div v-if="user.isPcAdmin" class="flex flex-ai-c">
                        <div class="">查看详情</div>
                        <div class="triangle"></div>
                    </div>
                </div>
            </div>
            <div class="block-content ">
                <div class="row">
                    <div class="">
                        <div class="key">余额（元）</div>
                        <div class="balance">
                            ￥<span class="number">{{ accountBalance }}</span>
                        </div>
                    </div>
                    <img class="img-chart" src="../assets/chart/chart-bar-blue.png" />
                </div>
                <button class="mini-btn recharge-btn" @click="longcz">充值</button>
            </div>
        </div>
        <div class="block ">
            <div class="block-header">
                <div class="block-title">当前在保人数</div>
                <div class="block-more point" @click="
                    $router.push({
                        path: '/long-insure/ensure'
                    })
                    ">
                    <div class="">查看详情</div>
                    <div class="triangle"></div>
                </div>
            </div>
            <div class="block-content">
                <div class="row">
                    <div class="">
                        <div class="key">人数</div>
                        <div class="number">
                            {{ allEnsureCount }}
                        </div>
                    </div>
                    <img class="img-chart" src="../assets/chart/chart-line-green.png" />
                </div>
            </div>
        </div>
        <div class="block">
            <div class="block-header">
                <div class="block-title">便捷导航</div>
                <div class="block-more">
                    <!-- <div class="">查看详情</div> -->
                    <!-- <div class="triangle"></div> -->
                </div>
            </div>
            <div class="block-content row nav">
                <div class="nav-item point" @click="
                    $router.push({
                        path: '/long-insure-dispatch'
                    })
                    ">
                    <img src="../assets/long-insure/dispatch.png" />
                    <div>被派遣单位</div>
                </div>
                <div class="nav-item point" @click="
                    $router.push({
                        path: '/long-insure-worker'
                    })
                    ">
                    <img src="../assets/long-insure/worker.png" />
                    <div>人员查询</div>
                </div>
                <div class="nav-item point" @click="
                    $router.push({
                        path: '/long-insure-report'
                    })
                    ">
                    <img src="../assets/long-insure/dispatch.png" />
                    <div>报案理赔</div>
                </div>
            </div>
        </div>
        <div class="block plan">
            <div class="block-header">
                <div class="block-title">我开通的方案</div>
                <!-- <span>方案名称</span> -->
            </div>
            <div class="block-content plan-list">
                <!-- isEnd -->
                <div v-for="(item, index) in companyPlans" v-bind:key="index"
                    :class="['plan-item point', item.isEnd ? 'disabled' : '']" @click="toInsureDetail(item.id)" :style="'background: url(' +
                        require('../assets/long-insure/plan-1.png') +
                        ')'
                        ">
                    <div class="plan-item-head">
                        <img class="item-head-img" :src="item.insurCompanyLogo" alt="" />
                        <div class="item-head-type">
                            {{ item.insurCompanyPlanName }}
                        </div>
                    </div>
                    <div class="plan-item-body">
                        <div class="item-body-describe">
                            <!--  -->
                            {{
                                item.type === 3
                                    ? "灵活保单"
                                    : item.type === 4
                                        ? "按月购买"
                                        : item.type === 5
                                            ? "及时生效"
                                            : ""
                            }}
                        </div>
                        <div class="item-body-count">
                            当前在保：{{ item.ensureCount }}人
                        </div>
                        <div class="item-body-count" v-if="item.isEnd">
                            到期时间：{{ item.endTime }}
                        </div>
                    </div>
                    <div class="plan-item-foot" v-if="!item.isEnd">
                        <button class="mini-btn recharge-btn">保障中</button>
                    </div>
                </div>
                <!-- 未激活状态 -->
                <!-- <div
                    class="plan-item"
                    :style="
                        'background: url(' +
                            require('../assets/long-insure/plan-4.png') +
                            ')'
                    "
                ></div> -->
                <!-- 添加 -->
                <!-- <div class="plan-item plan-add point">
                    <div class="plan-add-box">
                        <img class="img" src="../assets/long-insure/add.png" alt="">
                        <div>
                            添加保险方案
                        </div>
                    </div>
                </div> -->
            </div>
        </div>
        <div class="block premium-trend">
            <div class="block-header">
                <div class="block-title">保费趋势</div>
            </div>
            <div class="block-content">
                <el-empty v-if="isTrendEmpty" description="暂无数据" />
                <div id="trend"></div>
            </div>
        </div>
        <div class="block">
            <div class="block-header">
                <div class="block-title">人员统计</div>
                <div>
                    <el-select v-model="peopleStatisticsType" @change="onPeopleStatisticsType"
                        class="people-statistics-type">
                        <el-option :value="0" label="全部">全部</el-option>
                        <el-option :value="1" label="在保">在保</el-option>
                    </el-select>
                </div>
            </div>
            <div class="block-content">
                <el-empty v-if="
                    peopleStatistics?.occupationGroup?.length === 0 &&
                    statisticsTab === 0
                " description="暂无数据" />
                <el-empty v-if="
                    peopleStatistics?.serveCompanyGroup?.length === 0 &&
                    statisticsTab === 1
                " description="暂无数据" />
                <div class="flex-x-jus-btn mg-b-10">
                    <div class="mytab">
                        <div :class="{ 'tabitem': true, 'activetab': statisticsTab === 0 }"
                            @click="onPeopleStatisticsTab(0)">
                            工种({{ total1 }})</div>
                        <div :class="{ 'tabitem': true, 'activetab': statisticsTab === 1 }"
                            @click="onPeopleStatisticsTab(1)">
                            被派遣单位({{ total2 }})</div>
                    </div>
                    <div class="discrabe">
                        <div class="line"></div>
                        在保人数
                    </div>
                </div>
                <div v-if="statisticsTab === 0" class="infomsg">
                    <div v-for="(item, i) in listone" :key="i">
                        <div class="flex-x-jus-btn">
                            <div class="fc6B6B86 fs-12 mg-b-12">{{ item.occupationName }}</div>
                            <div class="fs-14">{{ item.count }}</div>
                        </div>
                        <div><el-progress :text-inside="true" :show-text="false"
                                :percentage="(item.count / maxone) * 100" /></div>
                    </div>
                </div>
                <div v-if="statisticsTab === 1" class="infomsg">
                    <div v-for="(item, i) in listtwo" :key="i">
                        <div class="flex-x-jus-btn">
                            <div class="fc6B6B86 fs-12 mg-b-12">{{ item.serveCompanyName }}</div>
                            <div class="fs-14">{{ item.count }}</div>
                        </div>
                        <div><el-progress :text-inside="true" :show-text="false"
                                :percentage="(item.count / maxtwo) * 100" /></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 增加投保弹窗 -->
        <el-dialog v-model="isDeletePopup" width="1400px" left="50%" top="5%">
            <div class="record">开通保险方案</div>
            <!-- <div class="record-top">
                <div class="top-name record-top-i">{{ personnelInfo[0].userName }}</div>
                <div class="rovalsState record-top-i">
                    <div class="decorate" :style="{background:personnelInfo[0].policyStatus == 1 ? '#00a854' : personnelInfo[0].policyStatus == 2 ? '#FF7E68' : '#1989FA'}" ></div>
                    {{ personnelInfo[0].policyStatus == 1 ? '保障中' : personnelInfo[0].policyStatus == 2 ? '不在保' : '待生效' }}
                </div>
                <div class="top-idcord record-top-i">{{ personnelInfo[0].encryptionIdCardNo }}</div>
            </div> -->
            <!-- <el-table
                    :header-cell-style="{background:'#F7F8FC'}"
                    :data="tableData2"
                    style="width: 100%"
                    :header-row-style="{ color: '#202536' }"
                    :row-style="{ color: '#5E617D' }"
                    @selection-change="handleSelectionChange"
                >
                <el-table-column type="index" label="序号" width="100px" />
                    <el-table-column
                        width="320px"
                        prop="serveCompanyName"
                        label="被派遣单位"
                    />
                <el-table-column prop="occupationName" label="工种"  />
                <el-table-column label="方案" prop="companyPlanName"  />
                <el-table-column prop="insurStartTime" label="开始时间" />
                <el-table-column class="card-no" prop="insurEndTime" label="结束时间" >
                    <template #default="scoped">
                        {{ scoped.row.insurEndTime || '暂无结束时间' }}
                    </template>
</el-table-column>
<el-table-column label="操作时间" prop="createTime" />
</el-table> -->
        </el-dialog>
        <!-- 充值方法 -->
        <popupRecharge v-if="isRecharge" @close="isRecharge = false" useWay="InsureRechargePeriodZgrs"
            :openBank="openBank" :bankNo="bankNo" :bankName="bankName" @determine="onDetermine" dataTitle="长期保充值">
        </popupRecharge>
        <div class="tc" @click.prevent="showtcflag = false" v-if="false">
            <div class="tcbox">
                <div class="tccontent">
                    <div class="top">
                        <div></div>
                        <div @click="closetc">
                            <img src="../assets/closetwo.png" alt="" />
                        </div>
                    </div>
                    <div class="bac2"></div>
                    <div class="ctbox">
                        <div class="tctext">
                            <div class="ctop">
                                <img src="../assets/block.png" alt="" /><span class="text">余额不足自动断保规则更新预告</span>
                            </div>
                            <p class="p">
                                当系统内<span class="boxshadle">余额不足</span>次日扣款(例如账户余额50元，次日需消耗100元)，将会在当日的
                                <span class="boxshadle">23:00分系统自动断保，人工无法干预。</span>
                            </p>
                            <p class="p">
                                在收到首次短信通知或者群里客服人员通知之后，请务必及时充值，
                                <span class="boxshadle">断保以后发生工伤</span>
                                <span class="boxshadle">将无法理赔。</span>
                            </p>
                        </div>
                        <div class="tctext">
                            <div class="ctop">
                                <img src="../assets/block.png" alt="" /><span class="text">特别约定</span>
                            </div>
                            <p class="p">
                                自2023年9月1日起，本保单所承接年龄超45周岁的保安或保洁人员因工作原因发生的猝死责任限额为主险责任限额的1/3。
                            </p>
                        </div>
                        <div class="tcbtnbox">
                            <div class="btn" @click="closetc">我知道了</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <sunny v-model:show="showSunnyDialog" />
    </div>
</template>
<script lang="ts">
import {
    getInsureData,
    getMoneyTrend,
    getPeopleStatistics,
    PlanStatisticsDto,
    addLongTermRecharge
} from '@/api/long-insure'
import { defineComponent } from 'vue'
import * as echarts from 'echarts'
import tabCapsule from '@/components/tab-capsule.vue'
import popupRecharge from '@/components/popup-recharge.vue'
import user from '@/utils/user'
import { ElMessage } from 'element-plus'
import sunny from '@/components/dialog/sunny.vue'
import { getUserInfo, getqueryreceiptaccountapi, getsaasCompanyinfoapi } from '../api/base'

console.log(2121212121, user.openBank)
export default defineComponent({
    name: 'LongInsure',
    components: { tabCapsule, popupRecharge, sunny },
    data() {
        return {
            listone: [],
            listtwo: [],
            maxone: 0,
            maxtwo: 0,
            total1: 0,
            total2: 0,
            showtcflag: true,
            accountBalance: '',
            allEnsureCount: '',
            companyPlans: [] as any,
            isDeletePopup: false,
            peopleStatistics: {} as PlanStatisticsDto,
            statisticsTab: 0,
            peopleStatisticsType: 0,
            isTrendEmpty: false,
            isRecharge: false,
            openBank: '',
            bankNo: '',
            bankName: '',
            showSunnyDialog: false,
            user: user
        }
    },
    async created() {
        // const data = await getUserInfo()
        const data: any = await getqueryreceiptaccountapi({ productType: 3 })
        console.log(data, '117843256398567348')
        this.openBank = data.openBank
        this.bankNo = data.bankNo
        this.bankName = data.bankName
        this.getInsureData()
        this.getMoneyTrend()
        this.onPeopleStatisticsType()
        if (sessionStorage.getItem('tcflag') === 'true') {
            this.showtcflag = true
        } else {
            this.showtcflag = false
        }
    },
    methods: {
        toInsureDetail(id: number) {
            this.$router.push({
                path: '/long-insure/detail/' + id
            })
        },
        closetc() {
            this.showtcflag = false
            sessionStorage.setItem('tcflag', 'true')
        },
        longcz() {
            if (this.accountBalance === null) {
                ElMessage({
                    type: 'warning',
                    message: '温馨提示：您还没有开通该功能权限，如有需要请联系销售'
                })
            } else {
                this.isRecharge = true
            }
        },
        async getInsureData() {
            // planList: result.companyPlans.map(item=>{
            //     item.isEnd = item.endTime ?  (new Date(item.endTime).getTime() < new Date().getTime()) : false
            //     return item;
            // })
            const result = await getInsureData()
            this.companyPlans = result.companyPlans
            this.accountBalance = result.accountBalance
            this.allEnsureCount = result.allEnsureCount

            const hasYg = this.companyPlans.some(
                (i: any) => i.insurCompany === 'period_003_yg'
            )

            if (hasYg && !localStorage.getItem('sunnyNoticeClose')) {
                this.showSunnyDialog = true
            }

            console.log(this.companyPlans, 'companyPlans')
        },
        async onPeopleStatisticsType() {
            await this.getPeopleStatistics()
            this.onPeopleStatisticsTab(this.statisticsTab)
        },
        async getPeopleStatistics() {
            this.total1 = 0
            this.total2 = 0
            let res: any = await getPeopleStatistics({
                policyStatus: this.peopleStatisticsType ? '1' : ''
            })
            console.log(res, 'gsuighiudsghuisuhi')
            let max1 = 0
            let max2 = 0
            if (res.occupationGroup.length !== 0) {
                res.occupationGroup.forEach((ele: any, i: number) => {
                    this.total1 += ele.count
                    if (max1 < ele.count) {
                        max1 = ele.count
                    }
                })
            }
            if (res.serveCompanyGroup.length !== 0) {
                res.serveCompanyGroup.forEach((ele: any, i: number) => {
                    this.total2 += ele.count
                    if (max2 < ele.count) {
                        max2 = ele.count
                    }
                })
            }
            this.maxone = max1
            this.maxtwo = max2
            this.listone = res.occupationGroup
            this.listtwo = res.serveCompanyGroup
            this.peopleStatistics = res
        },
        onPeopleStatisticsTab(tab: number) {
            this.statisticsTab = tab
            const element = document.getElementById(
                'people-statistics'
            ) as HTMLElement
            echarts.dispose(element)
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{b} <br/>{c}人  ({d}%)'
                },
                series: [
                    {
                        type: 'pie',
                        radius: ['60%', '80%'],

                        label: {
                            position: 'inner',
                            formatter: '{b} {c}人'
                        },
                        data: [] as { value: number; name: string }[]
                    }
                ]
            }
            const charts = echarts.init(element)
            if (tab === 0) {
                option.series[0].data = this.peopleStatistics.occupationGroup.map(
                    item => ({
                        value: item.count,
                        name: item.occupationName
                    })
                )
            } else {
                option.series[0].data = this.peopleStatistics.serveCompanyGroup.map(
                    item => ({
                        value: item.count,
                        name: item.serveCompanyName
                    })
                )
            }
            charts.setOption(option)
        },
        async getMoneyTrend() {
            const statistics = await getMoneyTrend()
            console.log(statistics, 'statistics')
            if (statistics?.length === 0) {
                this.isTrendEmpty = true
                return
            }
            console.log('打印啦吗')
            setTimeout(() => {
                const element = document.getElementById('trend') as HTMLElement
                console.log(element, 'element')
                echarts.dispose(element)
                const option = {
                    xAxis: {
                        type: 'category',
                        data: statistics.map(item => item.ensureDay)
                    },
                    yAxis: {
                        type: 'value'
                    },
                    grid: {
                        left: '30px',
                        right: '30px',
                        top: '30px',
                        bottom: '30px'
                    },
                    series: [
                        {
                            name: '人数',
                            data: statistics.map(item => item.peopleCount),
                            type: 'bar'
                        },
                        {
                            name: '金额',
                            data: statistics.map(item => item.money),
                            type: 'bar'
                        }
                    ]
                }
                console.log(option, 'option')
                const charts = echarts.init(element)
                charts.setOption(option)
                this.isTrendEmpty = false
            }, 300)
        },
        // 充值弹窗点击确定关闭
        async onDetermine(num: string, ocrNum:string, ocrImg: string, isRepeat: boolean) {
            if (!num) {
                this.$message.error('请输入金额')
                return
            }
            if (!ocrImg) {
                this.$message.error('请上传凭证')
                return
            }
            const result = await addLongTermRecharge({
                rechargeAmount: num,
                ocrAmount: ocrNum,
                voucherUrl: ocrImg,
                receiptId: user.receiptId,
                isRepeat: isRepeat
            })
            if (result) {
                // this.isRecharge = false
                this.$message.success('提交成功')
            }
        }
    }
})
</script>
<style scoped lang="stylus">
.container
    display grid
    grid-template-columns repeat(3, 1fr)
    grid-gap 16px
    margin-top 16px
.disabled
    filter grayscale(0.95)
.block
    padding 0
    width: 100%
    margin-top 0
.block-header
    space-between(false)
    border-bottom 1px solid #F7F8FC
    padding 14px 16px 8px
.block-title
    font-size font-small
    color black
    font-weight bold
.block-more
    display flex
    align-items center
    color color-blue
    .triangle
        margin-left 8px
        border-color color-blue transparent transparent transparent
        transform rotate(270deg)
        top 0
.block-content
    // space-between()
    padding 18px 16px
.premium-trend
    grid-column-end span 2
.plan
    grid-column-end span 3

.key
    font-size font-mini
    margin-bottom: 6px

.balance
    font-style italic

.number
    font-weight bold
    font-size font-large

.img-chart
    width 158px
    height 37px

.recharge-btn
    border-radius: 100px
    margin 16px 0 0
    height 28px
.nav
    padding 24px
    margin-top 8px
.nav-item
    text-align center
    font-size font-mini
    img
        margin-bottom 8px

.plan-list
    display grid
    grid-template-columns repeat(auto-fill, 264px)
    grid-gap 16px
.plan-item
    width 100%
    height: 183px;
    background-size 100% 100%
    padding 20px
    .plan-item-head
        display flex
        align-items center
    .item-head-img{
        width 28px
        height 28px
        border-radius 50%
        margin-right 8px
    }
    .item-head-type
        font-weight bold
        font-size 18px
        color #202536
    .plan-item-body
        padding-left 36px
        padding-top 16px
        color #202536
        font-size 14px
    .plan-item-foot
        margin-left 36px
.plan-add
    background-color #F7F8FC
    border-radius 8px
    border 1px dashed #DDE2FF
    display flex
    align-items center
    justify-content center
    .plan-add-box
        display flex
        flex-direction: column
        align-items center
        .img
            width 16px
            height 16px
            margin-bottom 9px
.record
    font-weight: #303133
    font-size 20px
    text-align center
    font-weight bold
.record-row
    text-align: center
    margin-top: 50px
    margin-bottom: 20px
.top
    font-weight: bold
    font-size: 15px
.idcord
    padding-left: 15px
.record-row span{
    padding-left: 20px
}
#trend
    margin-top 40px
#trend, #people-statistics
    width 100%
    height 300px
/deep/.tab-cap .tab
    width 90px
/deep/.people-statistics-type.el-select
    .el-input__inner
        border none
        width 80px
        color #1989FA
    .el-select__caret
        color #1989FA
    .el-input__icon,.el-input
        line-height 20px
    .el-input__inner
        height 20px
.tc
    z-index 9999999
    overflow auto
    width 100vw
    height 100vh
    position fixed
    top 0
    left 0
    background-color rgba(91, 91, 91,0.8)
    display flex
    align-items center
    justify-content center
.tctext
    background-color #D6F6E9
    width 100%
    min-height 100px
    margin-top 0
    box-sizing border-box
    border-radius 8px
    margin-bottom 16px
    box-sizing border-box
    padding 24px
    .p
        font-size 14px
        color #20362B
        margin 0
    .ctop
        display flex
        align-items center
        .text
            display inline-block
            margin-left 8px
            color #00C271
            font-size 20px
            font-weight 800
.ctbox
    margin-top -120px
.bac2
    width 100%
    height 225px
    background-image url(../assets/bac2.png)
    background-repeat no-repeat
    background-size 100%
    transform translateY(-60px)

.tcbox
    width 665px
    height 550px
.tccontent
    position relative
    overflow initial
    font-size 16px
    box-sizing border-box
    padding 0 40px
    width 100%
    height 450px
    background-image url(../assets/bg.png)
    background-repeat no-repeat
    background-size 100%
    border-radius 8px
.top
    position absolute
    width 100%
    height 50px
    display flex
    align-items center
    justify-content space-between
    top -80px
    left -5px
.tcbtnbox
    width 100%
    box-sizing border-box
    display flex
    align-items center
    justify-content center
    .btn
        background-color #00D679
        font-size 14px
        color #FFFFFF
        width 112px
        height 32px
        border-radius 16px
        text-align center
        line-height 32px
.boxshadle
    color #20362B
    font-weight bold
    position relative
    z-index 999999999

    &::after
        display block
        content''
        background linear-gradient(90deg, #E7F8F1 0%, #99F9D1 54%, #E7F8F1 100%)
        width 100%
        height 10px
        position absolute
        bottom 0
        left 0
        z-index -9
.infomsg
    background-color #F7F8FC
    border-radius 8px
    padding 20px
    display flex
    flex-direction column
    gap 16px
    width 100%
    box-sizing border-box
    height 300px
    overflow auto
    scrollbar-width none /* Firefox */
    -ms-overflow-style none /* IE 10+ */
    ::-webkit-scrollbar
        display none /* Chrome Safari */
.flex-x-jus-btn
    display flex
    align-items center
    justify-content space-between
.fc6B6B86
    color #6B6B86
.fs-12
    font-size 12px
.fs-14
    font-size 14px
.mytab
    display flex
    align-items center
    gap 12px
    .tabitem
        cursor pointer
        display flex
        align-items center
        justify-content center
        padding 8px 24px
        height 36px
        min-width 80px
        border-radius 4px
        background-color #F3F5FF
.activetab
    color #FFFFFF
    font-weight 600
    background-color #1989FA !important
.discrabe
    display flex
    align-items center
    gap 4px
    .line
        width 10px
        height 4px
        background-color #1989FA
</style>
